import {
  ModalForm,
  ProFormInstance,
  ProFormSelect,
} from '@ant-design/pro-form';
import { message } from 'antd';
import React, { useRef } from 'react';
import { useModel } from 'umi';

type FormProps = {
  visible: boolean;
  onCancel: () => void;
  onSubmit: (values: number[]) => Promise<void>;
};

const Form: React.FC<FormProps> = (props) => {
  const { visible, onCancel, onSubmit } = props;
  if (!visible) {
    return null;
  }

  const formRef = useRef<ProFormInstance>();

  const { getProductOptions } = useModel('useGlobalModel', (model) => ({
    getProductOptions: model.getProductOptions,
  }));

  const productOptions = getProductOptions(false);

  const handleFormSubmit = async () => {
    let productIds = formRef.current?.getFieldValue('productIds');
    console.log(productIds);
    if (!productIds) {
      message.error('请选择产品');
      return;
    }
    onSubmit(productIds);
  };

  return (
    <ModalForm<API.Product>
      layout="horizontal"
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 18 }}
      open={visible}
      title="批量修改服务器分组关联产品"
      width={640}
      formRef={formRef}
      onFinish={handleFormSubmit}
      modalProps={{
        onCancel: onCancel,
        //destroyOnClose: true,
        maskClosable: false,
      }}
    >
      <ProFormSelect
        mode="multiple"
        name="productIds"
        label="产品"
        options={productOptions}
        rules={[{ required: true, message: '请选择产品' }]}
      />
    </ModalForm>
  );
};

export default Form;
